<?php
/**
 *
 *@package 
 *@copyright Copyright (c) 2012-2014 Tuniu.com
 *@author huxiaomin 2012
 *@version 1.0
 */
  

class TMemcache{
	
	static $TM;
	public $number = D_MEMCACHE_NUMS;//分割基数
	

	static $servers = array();
	
	function __construct(){
	
		if (self::$servers){
			return self::$servers;
		}
		else {
			self::$servers = json_decode(D_MEMCACHE_CONFIG);
			return self::$servers;
		}
	}
	
	/**
	 * 取缓存
	 * @param $key
	 */
	function get($key){
		if (is_array($key)){
		  $return = array();
		  foreach ((array)$key as $v){
		      $return[$v] = $this->get($v);
		  }
		}else {
	       $memc = $this->getM($key);
	       $return = $memc->get($key);
		}
		return $return;
	}
	
	/**
	 * 设置缓存
	 * @param $key
	 * @param $var
	 * @param $flag
	 * @param $expire
	 */
	function set($key,$var,$flag=0, $expire=0 ){
	   $memc = $this->getM($key);
	   $flag = intval($flag);
	   $expire = intval($expire);
	   return $memc->set($key, $var, $flag, $expire);
	}
	
	/**
	 * 删除缓存
	 * @param $key
	 * @param $time_out
	 */
	function delete($key, $time_out=0){
	    $memc = $this->getM($key);
	    return $memc->delete($key, $time_out);
	}
	
	/**
	 *获取mem 
	 */
	private function getM($key){
	   $num  = $this->getNum($key);
       return $this->getMemcache($num);
	}
	
	/**
	 * 将key，hash到server上去。
	 * @param string $key
	 * @return int
	 */
    private function getNum($key){
       preg_match_all('/[0-9]/',md5($key),$matches);
       $sum = 0;
       foreach((array)$matches[0] as $v){
        $sum += $v;
       }
       return $num = $sum % $this->number;
    }
    
    /**
     * 返回memcache
     * @param $num
     */
    private function getMemcache($num){
    
        if (isset(self::$TM[$num])){
            return self::$TM[$num];
        } else {
            $memcache = new Memcache();
            $server = self::$servers[$num];
            $memcache->addserver($server[0],$server[1]);
            self::$TM[$num] = $memcache;
            return $memcache;
        }
    }
    
    
    
}